package yxy.game.pm2.command.stairway;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Format;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.StairwayMessage;
import yxy.game.pm2.module.hero.FormatHandle;
import yxy.game.pm2.module.stairway.StairwayHandle;
import yxy.game.pm2.module.stairway.StairwayPlayerModule;

import java.util.Collection;

/**
 * 天梯争雄 天梯挑战
 */
@MessageType(proto = Command.StairwayChanllenge, classtype = StairwayMessage.StairwayChanllengeRequest.class)
public class CMD_StairwayChanllenge extends Command<StairwayMessage.StairwayChanllengeRequest> {

    @Override
    public void execute(MessageSource messageSource, StairwayMessage.StairwayChanllengeRequest request) {
        String playerCode = messageSource.getTag();
        int rank = request.getRank();

        StairwayMessage.StairwayChanllengeResponse.Builder response = StairwayMessage.StairwayChanllengeResponse.newBuilder();

		PlayerBean playerBean = PlayerBean.get(playerCode);
		ServerBean serverBean = ServerBean.get(playerBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());

		boolean isOpen = StairwayHandle.isOpen(areaBean.getGroupId());
		if (!isOpen) {
			send(messageSource, response, Result.StairwayNotOpen);// 活动没有开始
			return;
		}

        StairwayPlayerModule stairwayPlayerModule = StairwayPlayerModule.get(playerCode);
        if (stairwayPlayerModule == null) {
            send(messageSource, response, Result.ModuleNotOpen);
            return;
        }

        FormatHandle formatHandle = new FormatHandle();
        Result result = formatHandle.check(playerCode, formatHandle.get(playerCode, Format.FormatType.普通));
        if (!result.equals(Result.Success)) {
            send(messageSource, response, result);   //  重复武将判断
            return;
        }

        // TODO 加锁
        Collection<Integer> oppos = stairwayPlayerModule.getOppos();
        for (Integer oppo : oppos) {
            if (oppo == rank) {
                result = new StairwayHandle().battleResponseExecute(stairwayPlayerModule, rank, response);
                send(messageSource, response, result);
                return;
            }
        }

        send(messageSource, response, Result.StairwayCantChanllenge);// 不能挑战这个位置的玩家
    }

    private void send(MessageSource messageSource, StairwayMessage.StairwayChanllengeResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }
}